package com.ly.feishu.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ly.feishu.entity.dto.AddTaskUserRequest;
import com.ly.feishu.entity.dto.TaskRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 飞书任务
 *
 * @author LiuYang
 * @since 2025/8/14 22:26
 **/
@Service
public class FeishuTaskService {

    @Autowired
    private FeishuTokenService tokenService;
    @Autowired
    private FeishuUserService userService;
    @Value("${feishu.api.create-task-url}")
    private String CREATE_TASK_URL;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 为指定用户创建待办任务
     *
     * @param task 任务
     * @return 飞书任务 ID
     */
    public String createTask(TaskRequest task) {
        String token = tokenService.getTenantAccessToken();
        String url = CREATE_TASK_URL;

        // 创建请求体：{"task": taskData}
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("summary", task.getSummary());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(url + "?receive_id_type=open_id", entity, String.class);

        try {
            JsonNode root = objectMapper.readTree(response.getBody());
            int code = root.path("code").asInt();
            if (code == 0) {
                return root.path("data").path("task").path("guid").asText();
            } else {
                throw new RuntimeException("创建任务失败: " + root.path("msg").asText());
            }
        } catch (Exception e) {
            throw new RuntimeException("解析响应失败: " + response.getBody(), e);
        }
    }


    /**
     * 为任务添加成员
     *
     * @param request request
     * @return 成功返回 true，否则抛出异常
     */
    public boolean addTaskUser(AddTaskUserRequest request) {
        String taskGuid = request.getTaskGuid();
        List<String> mobileList = request.getMobileList();

        String token = tokenService.getTenantAccessToken();
        String url = "https://open.feishu.cn/open-apis/task/v2/tasks/" + taskGuid + "/add_members";

        Map<String, String> openIdByMobile = userService.getOpenIdByMobile(mobileList);

        // 构建 members 数组
        List<Map<String, Object>> members = new ArrayList<>();
        for (String mobile : mobileList) {
            Map<String, Object> member = new HashMap<>();
            member.put("role", "assignee");
            member.put("id", openIdByMobile.get(mobile));
            members.add(member);
        }

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("members", members);

        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setBearerAuth(token);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            ResponseEntity<String> response = restTemplate.postForEntity(url, entity, String.class);

            if (response.getStatusCode() != HttpStatus.OK) {
                throw new RuntimeException("添加任务成员失败: HTTP " + response.getStatusCode() + ", 响应: " + response.getBody());
            }

            JsonNode respNode = objectMapper.readTree(response.getBody());
            int code = respNode.get("code").asInt();

            if (code != 0) {
                String msg = respNode.has("msg") ? respNode.get("msg").asText() : "未知错误";
                throw new RuntimeException("API 错误 (code=" + code + "): " + msg);
            }

            System.out.println("✅ 成功为任务 " + taskGuid + " 添加 " + mobileList.size() + " 个成员");
            return true;

        } catch (Exception e) {
            System.err.println("❌ 添加任务成员异常: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
}
